// 搜索类，获取历史搜索等
let en_js = require('/environment.js');

//保存搜索信息
function saveSearchInfo(info) {
  wx.setStorageSync(en_js.searchInfoKey, info);
}

//获取搜索信息
function searchInfo() {
  let value = wx.getStorageSync(en_js.searchInfoKey);
  if (value) {
    return value;
  } else {
    return null;
  }
}

//获取搜索历史列表
function historyList() {
  let value = searchInfo();
  if (!value) return [];
  return value.historyList;
}

//清空搜索历史信息
function clearHistory() {
  let value = searchInfo();
  if (!value) return;
  value.historyList = [];
  //save
  saveSearchInfo(value);
}

//保存搜索历史
function addHistoryWithKeyWord(keyWord) {
  let value = searchInfo();
  if (value) {
    let historyList = value.historyList;
    let tmpSet = new Set(historyList);
    let keyWordSet = new Set([keyWord]);
    let intersect = [...new Set([...tmpSet].filter(n => keyWordSet.has(n)))];
    if (Array.from(intersect).length > 0) {
      return;
    } else {
      //最多保存10个历史记录
      //在首位添加keyWord
      historyList.splice(0, 0, keyWord);
      if (historyList.length > 10) {
        historyList.splice(10, 1);
      }
    }
    value.historyList = historyList;
  } else {
    let list = [];
    list.push(keyWord);
    let searchOjb = {};
    searchOjb.historyList = list;
    value = searchOjb;
  }
  //save
  saveSearchInfo(value);
}

module.exports = {
  historyList: historyList,
  clearHistory: clearHistory,
  addHistoryWithKeyWord: addHistoryWithKeyWord
}